require("../../assets/css/normalize.css");
require("../../assets/css/reset.css");
require("./register.less");

// 引入字体图标的css文件
require("../../assets/fonts/iconfont.css");

// 引入axios
let axios = require("axios");

// 引入验证码插件
const CaptchaMini = require("captcha-mini");

// 引入获取节点的手写插件
const dom = require("../../utils/dom.js");

// 设置验证码
let captcha = new CaptchaMini();
let codeN = "";
captcha.draw(dom.get("#captcha"), (r) => {
	codeN = r.toLowerCase();
});

window.addEventListener("DOMContentLoaded", function () {
	dom.get("button").addEventListener("click", function () {
		// 获取手机号码框的值
		const tel = dom.get("#tel").value;
		// 获取验证码框的值并转为小写
		const code = dom.get("#code").value.toLowerCase();
		// 获取密码框的值
		const pwd = dom.get("#pwd").value;
		// 获取确认密码框的值
		const pwd1 = dom.get("#pwd1").value;

		// 验证手机号
		let reg = /^1[3456789]\d{9}$/;
		if (reg.test(tel)) {
			dom.get(".error").textContent = "";
		} else {
			dom.get(".error").style.color = "#f00";
			dom.get(".error").textContent = "请输入正确的手机号";
			return;
		}

		// 验证码
		if (code === codeN) {
			dom.get(".error").textContent = "";
		} else {
			dom.get(".error").style.color = "#f00";
			dom.get(".error").textContent = "验证码错误";
			return;
		}

		// 验证密码
		if (pwd.length >= 6) {
			dom.get(".error").textContent = "";
		} else {
			dom.get(".error").style.color = "#f00";
			dom.get(".error").textContent = "请设置至少六位数的密码";
			return;
		}

		// 确认密码
		if (pwd1 === pwd) {
			dom.get(".error").textContent = "";
		} else {
			dom.get(".error").style.color = "#f00";
			dom.get(".error").textContent = "两次输入密码不一致";
			return;
		}

		axios
			.post("http://fitness.h5.itsource.cn:3701/api/user/register", {
				account: tel,
				password: pwd,
			})
			.then((res) => {
				console.log(res);
				if (res.data.errno === 0) {
					dom.get(".error").textContent = "注册成功";
					dom.get(".error").style.color = "#0f0";
					location.href = "./login.html";
				} else {
					dom.get(".error").textContent = res.data.message;
				}
			});
	});
});
